package com.example.demofdfs.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.example.demofdfs.model.CommandResutl;

public class CommandUtil {

	public static CommandResutl exec(String... cmd) {
		
		Runtime runtime = Runtime.getRuntime();
		CommandResutl commandResult = null;
		String result = null;
		String error = null;
		try {
			Process process = runtime.exec(cmd);
			result = input(process.getInputStream());
			error = input(process.getErrorStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (result != null)
			commandResult = new CommandResutl(result, null, CommandResutl.SUCCESS_CODE);
		else if (error != null)
			commandResult = new CommandResutl(null, error, CommandResutl.ERROR_CODE);
		
		System.out.println(commandResult);
		
		return commandResult;
	}
	
	private static String input(InputStream inputStream) {
		
		BufferedInputStream buff = new BufferedInputStream(inputStream);
		
		byte[] b = new byte[1024];
		int len;
		StringBuilder sb = new StringBuilder();
		try {
			while((len = buff.read(b)) > -1) 
				sb.append(new String(b, 0, len, getCharset()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static String getCharset() {
		String os = System.getProperty("os.name");
		String charset;
		if (os.toLowerCase().indexOf("window") > -1)
			charset = "gb2312";
		else if (os.toLowerCase().indexOf("linux") > -1)
			charset = "UTF-8";
		else
			charset = "UTF-8";
		
		return charset;
	}
	
	public static void main(String[] args) throws IOException {
//		String [] cmd={"cmd", "/C", "netstat -ano"}; 
//		String [] cmd={"cmd", "/C", "ping localhost"}; 
		String [] cmd={"cmd", "/C", "xxx"}; 
		exec(cmd);
	}
}
